

function initRole_add(){
	var url="function_query.shtml";
	
	$.get(url,function(treeData){
		treeData = eval(treeData);
		var root = {id:0,pId:0,name:"功能结构树",nocheck:true};
		treeData.push(root);
		treeData=createCheckBoxToTree(treeData);
		var functionTree=$.fn.zTree.init($("#treeForRole_Add"), {
			data: {
				simpleData: {
					enable: true
				}
			},
		   check:{
				enable:true
			},
		   callback:{
				//复选框被操作时的处理函数
				
				onCheck:function(event,treeId,treeNode){
				 //将read节点的复选框设置为选中
					if(treeNode.checked&&treeNode.name != "查询"){
						var pNode = treeNode.getParentNode();
						$.each(pNode.children,function(i,child){
							if(child.name=="查询"&&(!child.checked)){
								child.checked=true;
								$.fn.zTree.getZTreeObj(treeId).updateNode(child);
							}
						});
					}
				}
			}
		}, treeData);
		functionTree.expandAll(true);
	})
}

function createCheckBoxToTree(treeData){
	  $.each(treeData,function(i,node){
		   if(node.fLevel==1 || node.fLevel==0){
			   node.nocheck=true;
		   }
		   if(node.fLevel==2){
			   var checkCreate = node.id+"_C";
			   var check_Node_Create={id:node.id+"_C",pId:node.id,name:"增加",oper:"c"};
			   var check_Node_Delete={id:node.id+"_D",pId:node.id,name:"删除",oper:"d"};
			   var check_Node_Update={id:node.id+"_U",pId:node.id,name:"更新",oper:"u"};
			   var check_Node_Read={id:node.id+"_R",pId:node.id,name:"查询",oper:"r"};
			   treeData=treeData.concat([check_Node_Create,check_Node_Delete,check_Node_Update,check_Node_Read]);
		   }
	   });
	   return treeData;
}

function role_add_update(url,roleName,treeName){
	// 添加角色处理函数
	debugger
	var checkedNodes = $.fn.zTree.getZTreeObj(treeName).getCheckedNodes(true);
	
	if(!roleName){
		roleName = $("#txtRoleName").val();
	}
	var postObj={roleName:roleName,roleWithFunctions:[]};

	$.each(checkedNodes,function(i,node){
		if(node.level==2){
			var ruleObj ={functionId:node.id,c:false,u:false,r:false,d:false};
			$.each(node.children,function(i,subNode){
				switch (subNode.oper) {
				case "c":
					ruleObj.c = subNode.checked;
					break;
				case "u":
					ruleObj.u = subNode.checked;
					break;
				case "r":
					ruleObj.r = subNode.checked;
					break;
				case "d":
					ruleObj.d = subNode.checked;
					break;
				default:
					break;
				}
			})
			if(ruleObj.c || ruleObj.u || ruleObj.d){
				ruleObj.r =true;
			}
			postObj.roleWithFunctions.push(ruleObj);
		}
	});
	
	$.post(url,{
		"ruleObj":JSON.stringify(postObj)
	},onSaveRuleSuccess);
}

function onSaveRuleSuccess(rlt){
	if(rlt=='true'){
		alert("成功!");
	}
	else{
		alert(rlt);
	}
}

function role_query(){
	var role_cols =  [
                      {display: '编号', name : 'id', width : 50, sortable : true, align: 'center',hide: false,toggle : false},
          			 {display: '角色名称', name : 'role_name', width : 150, sortable : true, align: 'center'},
          			 {display: '备注', name : 'role_remarks', width : 350, sortable : true, align: 'center'},
          		     ];

	var role_buttons =   [ 
	                      				//{ name:'查看',displayname:'查看' ,bclass:'query',onpress:displayFunction},
	                      				//{separator: true},
	         				 			{ name: '修改', displayname: '修改', bclass: 'modify', onpress: editFunction },
	         				 			{separator: true},
	         				 			{ name: '删除',displayname: '删除', bclass: 'delete', onpress: onRoleDelete }
	         				 	   ];
	var roleName = $("#txtRoleName_query").val();
	var url=encodeURI("role_query.shtml?rolename="+roleName);
	var setting ={
			   width: 700,
			   height: 280,
			   url: url,
			   dataType: 'json',
			   colModel :role_cols,
				buttons:role_buttons, 
				searchitems : [
				  {display: '编号', name : 'id', isdefault: true},
				  {display: '角色名称', name : 'role_name'}
				],
				errormsg: '发生异常',
				sortname: "id",
				sortorder: "desc",
				usepager: true,
				title: '角色记录',
				pagestat: '显示记录从{from}到{to}，总数{total}条',
				useRp: true, 
				rp: 10, 
				rpOptions: [10, 15, 20, 30, 40, 100],
				nomsg: '没有符合条件的记录存在',
				minColToggle: 1, 
				showTableToggleBtn: false, 
				autoload: true,
				resizable: false, 
				pagetext: '页',
		       outof: '共',
		       findtext: '查找',
		       pagestat: "当前显示记录{from}到{to}条，总{total}条",
				procmsg: '加载中, 请稍等 ...', 
				singleSelect:true,
				//onRowSelect:selectRow,
				onSuccess:onTableSuccess,
				//hideOnSubmit: true, 
				//blockOpacity: 0.5, 
				//showcheckbox: true, 
				//gridClass: "bbit-grid",
			   // rowhandler: true, 
				//rowbinddata: true, 
				//onrowchecked: callme ,
				preProcess:onRolePreProcess
			  };
	$("#roleTable").flexigrid(setting);
	$("#roleTable").flexOptions(setting).flexReload();
}

function onRoleDelete(com,grid){
    var selected_count = $('.trSelected', grid).length;
	 
    if (selected_count != 1) {
        alert("请选择一条记录！");
        return;
    }
    else {
        var role_id = parseInt($(".trSelected td>div", grid)[0].textContent);
        var url = encodeURI("role_delete.shtml?role_id="+role_id);
        $.get(url,function(data){
        	if(data=="true"){
        		alert("删除成功！");
        		role_query();
        	}
        	else{
        		alert("删除失败！");
        	}
        });
    }
}

function onRolePreProcess(data){
    var newData;
    if (data != null) {
        var rows = [];
        for (var i = 0; i < data.rows.length; i++) {
            var cellContent = [];
            cellContent.push("<div style='height:10px;'>" + data.rows[i].cell.id + "</div>");
            cellContent.push("<input type='text' style='width:200px;height:20px;font-family:微软雅黑' value='" + data.rows[i].cell.role_name + "' />");
            cellContent.push("<input type='text' style='width:200px;height:20px;font-family:微软雅黑' value='" + data.rows[i].cell.role_remarks + "' />");
            var content = {
                cell: cellContent
            };
            rows.push(content);
        }
        newData = {
            total: data.total,
            page: data.page,
            rows: rows
        };
        return newData;
    }
}

function onTableSuccess(){
	$("#roleTable tr").click(function() {
		displayFunction(null,$("#roleTable"));
	});
}

function displayFunction(oper,grid){
	var selected = $(".trSelected", grid).length;
	if(selected<=0){
		alert("请选择一行！");
		return;
	}
	var roleId = $(".trSelected td[abbr=id]", grid).text();
	var url="roleFunction_query.shtml?role_id="+roleId;
	$.get(url,function(data){
		data = $.parseJSON(data);
		var root = {id:0,pId:0,name:"功能结构树",nocheck:true};
		var treeData = data.listTreeNodes;
		treeData.push(root);
		treeData=addCheckBoxForRoleFunctionQuery(treeData,data.listRoleWithFunctions);
		var treeSetting = {
		   data: {
			simpleData: {
				enable: true
			}
			},
			check:{
				enable:true
			},
			callback:{
				onCheck:onTreeCheck
			}
		}
		var functionTree=$.fn.zTree.init($("#treeForRole_Query"),treeSetting,treeData);
		functionTree.expandAll(true);
	})
}

function onTreeCheck(event,treeId,treeNode){
	 //将read节点的复选框设置为选中
		if(treeNode.checked&&treeNode.name != "查询"){
			var pNode = treeNode.getParentNode();
			$.each(pNode.children,function(i,child){
				if(child.name=="查询"&&(!child.checked)){
					child.checked=true;
					$.fn.zTree.getZTreeObj(treeId).updateNode(child);
				}
			});
		}
}

function editFunction(oper,grid){
    var selected_count = $('.trSelected', grid).length;
    debugger
    if (selected_count != 1) {
        alert("请选择一条记录！");
        return;
    }
    else {
        var rolename= $(".trSelected td>div", grid)[1].children[0].value;
	    role_add_update("role_update.shtml",rolename,'treeForRole_Query');
    }
}

 function addCheckBoxForRoleFunctionQuery(treeData,roleFunctionList){
	  $.each(treeData,function(i,node){
		   if(node.fLevel==1 || node.fLevel==0){
			   node.nocheck=true;
		   }
		   if(node.fLevel==2){
			   var roleFunction = judgeHasFunctionOper(node.id,roleFunctionList);
			   var check_Node_Create={id:node.id+"_C",pId:node.id,name:"增加",oper:"c",checked:roleFunction?roleFunction.c:false};
			   var check_Node_Delete={id:node.id+"_D",pId:node.id,name:"删除",oper:"d",checked:roleFunction?roleFunction.d:false};
			   var check_Node_Update={id:node.id+"_U",pId:node.id,name:"更新",oper:"u",checked:roleFunction?roleFunction.u:false};
			   var check_Node_Read={id:node.id+"_R",pId:node.id,name:"查询",oper:"r",checked:roleFunction?roleFunction.r:false};
			   treeData=treeData.concat([check_Node_Create,check_Node_Delete,check_Node_Update,check_Node_Read]);
			   if(check_Node_Create.checked || check_Node_Delete.checked || check_Node_Update.checked || check_Node_Read.checked){
				   node.checked = true;
			   }
		   }
	   });
	   return treeData;
}
 
 function judgeHasFunctionOper(nodeId,roleFunction){
	 var rlt =null;
	 $.each(roleFunction,function(i,value){
		 if(nodeId==value.functionId){
			rlt=value;
		 }
	 })
	 return rlt;
 }

